package org.jeecg.modules.manage.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.jeecg.cmbCloudDirectLink.utils.CMBApi;
import org.jeecg.common.api.dto.BankSetDTO;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.vo.SelectTreeModel;
import org.jeecg.common.util.TokenUtils;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.manage.entity.CaishuiBusiness;
import org.jeecg.modules.manage.entity.CaishuiBusinessBank;
import org.jeecg.modules.manage.entity.CaishuiMiddleCompany;
import org.jeecg.modules.manage.entity.CaishuiServiceCompany;
import org.jeecg.modules.manage.mapper.MCaishuiBusinessMapper;
import org.jeecg.modules.manage.service.IMCaishuiBusinessBankService;
import org.jeecg.modules.manage.service.IMCaishuiBusinessService;
import org.jeecg.modules.manage.service.IMCaishuiCompanySetService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @Description: 商户基本信息表
 * @Author: yfkj
 * @Date:   2023-02-07
 * @Version: V1.0
 */
@Service
public class MCaishuiBusinessServiceImpl extends ServiceImpl<MCaishuiBusinessMapper, CaishuiBusiness> implements IMCaishuiBusinessService {

    @Autowired
    private IMCaishuiBusinessBankService imCaishuiBusinessBankService;
    @Autowired
    private IMCaishuiCompanySetService imCaishuiCompanySetService;

	@Override
	public void addCaishuiBusiness(CaishuiBusiness caishuiBusiness) {
	   //新增时设置hasChild为0
	    caishuiBusiness.setHasChild(IMCaishuiBusinessService.NOCHILD);
		if(oConvertUtils.isEmpty(caishuiBusiness.getPid())){
			caishuiBusiness.setPid(IMCaishuiBusinessService.ROOT_PID_VALUE);
		}else{
			//如果当前节点父ID不为空 则设置父节点的hasChildren 为1
			CaishuiBusiness parent = baseMapper.selectById(caishuiBusiness.getPid());
			if(parent!=null && !"1".equals(parent.getHasChild())){
				parent.setHasChild("1");
				baseMapper.updateById(parent);
			}
		}
		baseMapper.insert(caishuiBusiness);
	}
	
	@Override
	public void updateCaishuiBusiness(CaishuiBusiness caishuiBusiness) {
		CaishuiBusiness entity = this.getById(caishuiBusiness.getId());
		if(entity==null) {
			throw new JeecgBootException("未找到对应实体");
		}
		String old_pid = entity.getPid();
		String new_pid = caishuiBusiness.getPid();
		if(!old_pid.equals(new_pid)) {
			updateOldParentNode(old_pid);
			if(oConvertUtils.isEmpty(new_pid)){
				caishuiBusiness.setPid(IMCaishuiBusinessService.ROOT_PID_VALUE);
			}
			if(!IMCaishuiBusinessService.ROOT_PID_VALUE.equals(caishuiBusiness.getPid())) {
				baseMapper.updateTreeNodeStatus(caishuiBusiness.getPid(), IMCaishuiBusinessService.HASCHILD);
			}
		}
		baseMapper.updateById(caishuiBusiness);
	}
	
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void deleteCaishuiBusiness(String id) throws JeecgBootException {
		//查询选中节点下所有子节点一并删除
        id = this.queryTreeChildIds(id);
        if(id.indexOf(",")>0) {
            StringBuffer sb = new StringBuffer();
            String[] idArr = id.split(",");
            for (String idVal : idArr) {
                if(idVal != null){
                    CaishuiBusiness caishuiBusiness = this.getById(idVal);
                    String pidVal = caishuiBusiness.getPid();
                    //查询此节点上一级是否还有其他子节点
                    List<CaishuiBusiness> dataList = baseMapper.selectList(new QueryWrapper<CaishuiBusiness>().eq("pid", pidVal).notIn("id",Arrays.asList(idArr)));
                    boolean flag = (dataList == null || dataList.size() == 0) && !Arrays.asList(idArr).contains(pidVal) && !sb.toString().contains(pidVal);
                    if(flag){
                        //如果当前节点原本有子节点 现在木有了，更新状态
                        sb.append(pidVal).append(",");
                    }
                }
            }
            //批量删除节点
            baseMapper.deleteBatchIds(Arrays.asList(idArr));
            //修改已无子节点的标识
            String[] pidArr = sb.toString().split(",");
            for(String pid : pidArr){
                this.updateOldParentNode(pid);
            }
        }else{
            CaishuiBusiness caishuiBusiness = this.getById(id);
            if(caishuiBusiness==null) {
                throw new JeecgBootException("未找到对应实体");
            }
            updateOldParentNode(caishuiBusiness.getPid());
            baseMapper.deleteById(id);
        }
	}
	
	@Override
    public List<CaishuiBusiness> queryTreeListNoPage(QueryWrapper<CaishuiBusiness> queryWrapper) {
        List<CaishuiBusiness> dataList = baseMapper.selectList(queryWrapper);
        List<CaishuiBusiness> mapList = new ArrayList<>();
        for(CaishuiBusiness data : dataList){
            String pidVal = data.getPid();
            //递归查询子节点的根节点
            if(pidVal != null && !IMCaishuiBusinessService.NOCHILD.equals(pidVal)){
                CaishuiBusiness rootVal = this.getTreeRoot(pidVal);
                if(rootVal != null && !mapList.contains(rootVal)){
                    mapList.add(rootVal);
                }
            }else{
                if(!mapList.contains(data)){
                    mapList.add(data);
                }
            }
        }
        return mapList;
    }

    @Override
    public List<SelectTreeModel> queryListByCode(String parentCode) {
        String pid = ROOT_PID_VALUE;
        if (oConvertUtils.isNotEmpty(parentCode)) {
            LambdaQueryWrapper<CaishuiBusiness> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(CaishuiBusiness::getPid, parentCode);
            List<CaishuiBusiness> list = baseMapper.selectList(queryWrapper);
            if (list == null || list.size() == 0) {
                throw new JeecgBootException("该编码【" + parentCode + "】不存在，请核实!");
            }
            if (list.size() > 1) {
                throw new JeecgBootException("该编码【" + parentCode + "】存在多个，请核实!");
            }
            pid = list.get(0).getId();
        }
        return baseMapper.queryListByPid(pid, null);
    }

    @Override
    public List<SelectTreeModel> queryListByPid(String pid) {
        if (oConvertUtils.isEmpty(pid)) {
            pid = ROOT_PID_VALUE;
        }
        return baseMapper.queryListByPid(pid, null);
    }

	/**
	 * 根据所传pid查询旧的父级节点的子节点并修改相应状态值
	 * @param pid
	 */
	private void updateOldParentNode(String pid) {
		if(!IMCaishuiBusinessService.ROOT_PID_VALUE.equals(pid)) {
			Long count = baseMapper.selectCount(new QueryWrapper<CaishuiBusiness>().eq("pid", pid));
			if(count==null || count<=1) {
				baseMapper.updateTreeNodeStatus(pid, IMCaishuiBusinessService.NOCHILD);
			}
		}
	}

	/**
     * 递归查询节点的根节点
     * @param pidVal
     * @return
     */
    private CaishuiBusiness getTreeRoot(String pidVal){
        CaishuiBusiness data =  baseMapper.selectById(pidVal);
        if(data != null && !IMCaishuiBusinessService.ROOT_PID_VALUE.equals(data.getPid())){
            return this.getTreeRoot(data.getPid());
        }else{
            return data;
        }
    }

    /**
     * 根据id查询所有子节点id
     * @param ids
     * @return
     */
    private String queryTreeChildIds(String ids) {
        //获取id数组
        String[] idArr = ids.split(",");
        StringBuffer sb = new StringBuffer();
        for (String pidVal : idArr) {
            if(pidVal != null){
                if(!sb.toString().contains(pidVal)){
                    if(sb.toString().length() > 0){
                        sb.append(",");
                    }
                    sb.append(pidVal);
                    this.getTreeChildIds(pidVal,sb);
                }
            }
        }
        return sb.toString();
    }

    /**
     * 递归查询所有子节点
     * @param pidVal
     * @param sb
     * @return
     */
    private StringBuffer getTreeChildIds(String pidVal,StringBuffer sb){
        List<CaishuiBusiness> dataList = baseMapper.selectList(new QueryWrapper<CaishuiBusiness>().eq("pid", pidVal));
        if(dataList != null && dataList.size()>0){
            for(CaishuiBusiness tree : dataList) {
                if(!sb.toString().contains(tree.getId())){
                    sb.append(",").append(tree.getId());
                }
                this.getTreeChildIds(tree.getId(),sb);
            }
        }
        return sb;
    }


    /**
     * 新增默认商户
     * @param company
     * @param middleCompany
     */
    @Override
    public void addDefaultBusiness(CaishuiServiceCompany company, CaishuiMiddleCompany middleCompany){
        //默认商户
        CaishuiBusiness caishuiBusiness = new CaishuiBusiness();
        caishuiBusiness.setType(1);
        caishuiBusiness.setName(company.getBankAccount());
        caishuiBusiness.setPhone(company.getContactPhone());
        caishuiBusiness.setTax(company.getBusinessLicenseNo());
        caishuiBusiness.setLegal(company.getLegalName());
        caishuiBusiness.setLegalPhone(company.getContactPhone());
        caishuiBusiness.setBankName(company.getBankName());
        caishuiBusiness.setBankAccount(company.getBankCard());
        caishuiBusiness.setIdCardZm(company.getLegalSfzZm());
        caishuiBusiness.setIdCardFm(company.getLegalSfzFm());
        caishuiBusiness.setBusinessLicense(company.getBusinessLicensePhoto());
        caishuiBusiness.setContractFile(company.getContractFile());
        caishuiBusiness.setStatus(1);
        caishuiBusiness.setTenantId(middleCompany.getTenantId());
        caishuiBusiness.setUserId(TokenUtils.getLoginUser().getId());
        caishuiBusiness.setCreateBy(TokenUtils.getLoginUser().getRealname());
        caishuiBusiness.setIsDefault(1);

        /**添加默认父商户*/
        CaishuiBusiness business1 = new CaishuiBusiness();
        BeanUtils.copyProperties(caishuiBusiness,business1);
        business1.setPid("0");
        business1.setHasChild("1");
        this.baseMapper.insert(business1);

        //根据账号查询服务公司设置相关信息
        BankSetDTO bankSetDTO = imCaishuiCompanySetService.queryCompanySet(company.getBankCard());

        /**添加默认商户税费子账户——商户信息*/
        //判断税费子账户是否已存在
        long count2 = imCaishuiBusinessBankService.count(new LambdaQueryWrapper<CaishuiBusinessBank>()
                .eq(CaishuiBusinessBank::getServiceCompanyId,company.getId()).eq(CaishuiBusinessBank::getType,2));
        if (count2 > 0) throw new JeecgBootException("该服务公司下已存在税费子账户！");
        CaishuiBusiness business2 = new CaishuiBusiness();
        BeanUtils.copyProperties(caishuiBusiness,business2);
        business2.setName(company.getBankAccount() + "税费子账户");
        business2.setPid(business1.getId());
        business2.setHasChild("0");
        this.baseMapper.insert(business2);

        /**添加默认商户税费子账户——银行信息*/
        //记账子单元编号
        String subAccountId2 = "100001";
        //新增记账子单元
        Result result2 = CMBApi.addBookkeepingSubUnit(company.getBankCard(),subAccountId2,business2.getName(), bankSetDTO);
        if(!result2.isSuccess()){
            throw new JeecgBootException(result2.getMessage());
        }
        CaishuiBusinessBank caishuiBusinessBank2 =  new CaishuiBusinessBank();
        caishuiBusinessBank2.setTenantId(business2.getTenantId());
        caishuiBusinessBank2.setBusinessId(business2.getId());
        caishuiBusinessBank2.setServiceCompanyId(company.getId());
        caishuiBusinessBank2.setSubAccountId(subAccountId2);//记账子单元编号
        caishuiBusinessBank2.setAccountName(business2.getName());//户名
        caishuiBusinessBank2.setMainAccount(company.getBankCard());//主账号（服务公司账号）
        caishuiBusinessBank2.setAccount(company.getBankCard() + subAccountId2);//打款账户（15位主账户+子单元）
        caishuiBusinessBank2.setBankName(company.getBankName());//打款开户行
        caishuiBusinessBank2.setName(company.getBankAccount());//打款户名
        caishuiBusinessBank2.setTaxRate(0.0000);
        caishuiBusinessBank2.setType(2);
        imCaishuiBusinessBankService.save(caishuiBusinessBank2);

        /**添加默认商户用工子账户——商户信息*/
        CaishuiBusiness business3 = new CaishuiBusiness();
        BeanUtils.copyProperties(caishuiBusiness,business3);
        business3.setName(company.getBankAccount() + "用工子账户");
        business3.setPid(business1.getId());
        business3.setHasChild("0");
        this.baseMapper.insert(business3);

        /**添加默认商户用工子账户——银行信息*/
        //记账子单元编号
        String subAccountId3 = "100002";
        //新增记账子单元
        Result result3 = CMBApi.addBookkeepingSubUnit(company.getBankCard(),subAccountId3,business3.getName(), bankSetDTO);
        if(!result3.isSuccess()){
            throw new JeecgBootException(result3.getMessage());
        }
        CaishuiBusinessBank caishuiBusinessBank3 =  new CaishuiBusinessBank();
        caishuiBusinessBank3.setTenantId(business3.getTenantId());
        caishuiBusinessBank3.setBusinessId(business3.getId());
        caishuiBusinessBank3.setServiceCompanyId(company.getId());
        caishuiBusinessBank3.setSubAccountId(subAccountId3);//记账子单元编号
        caishuiBusinessBank3.setAccountName(business3.getName());//户名
        caishuiBusinessBank3.setMainAccount(company.getBankCard());//主账号（服务公司账号）
        caishuiBusinessBank3.setAccount(company.getBankCard() + subAccountId3);//打款账户（15位主账户+子单元）
        caishuiBusinessBank3.setBankName(company.getBankName());//打款开户行
        caishuiBusinessBank3.setName(company.getBankAccount());//打款户名
        caishuiBusinessBank3.setTaxRate(0.0000);
        caishuiBusinessBank3.setType(1);
        imCaishuiBusinessBankService.save(caishuiBusinessBank3);
    };

}
